﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Windows.Navigation;
using System.IO;
using Newtonsoft.Json.Linq;
using Tuzzit_Modele;
using Microsoft.Phone.Tasks;
using System.Resources;

namespace Tuzzit
{
    public partial class ProjetsPivot : PhoneApplicationPage
    {
        string hash;
        String pname;

        public ProjetsPivot()
        {
            InitializeComponent();
            HeaderIdea.Header = AppResources.ProjetPivotIdeaTitle;
            HeaderTask.Header = AppResources.ProjetPivotTaskTitle;
            HeaderDoc.Header = AppResources.ProjetPivotDocTitle;
            HeaderTeam.Header = AppResources.ProjetPivotTeamTitle;
            //AppbarAddItem.Text = AppResources.ProfilPivotApplicationbarAddProject;
            //AppbarRefreshItem.Text = AppResources.ProfilPivotApplicationbarRefreshProject;
            //logout.Text = AppResources.ProfilPivotApplicationbarLogout;
            //about.Text = AppResources.ProfilPivotApplicationbarAbout;
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (e.NavigationMode == NavigationMode.Back) return;

            NavigationContext.QueryString.TryGetValue("hash", out hash);
            NavigationContext.QueryString.TryGetValue("pname", out pname);
            ProjetPivot.Title = pname;
            GetTask();
            GetIdea();
            GetDoc();
            GetTeam();
        }


        private void GetTask()
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://dev.tuzzit.com/exec/task_controller.php?function=get_task_list&format=json&params%5Bhashcode%5D=" + hash);
            request.CookieContainer = new CookieContainer();
            request.CookieContainer.Add(new Uri("http://dev.tuzzit.com"), (Application.Current as App).Cookies);
            request.BeginGetResponse(new AsyncCallback(ReadWebRequestCallbackTask), request);
        }

        private void ReadWebRequestCallbackTask(IAsyncResult callbackResult)
        {
            HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
            HttpWebResponse myResponse = (HttpWebResponse)myRequest.EndGetResponse(callbackResult);

            (Application.Current as App).Cookies = myResponse.Cookies;

            using (StreamReader httpwebStreamReader = new StreamReader(myResponse.GetResponseStream()))
            {
                string results = httpwebStreamReader.ReadToEnd();
                // Dispatcher.BeginInvoke(() => MessageBox.Show(results.ToString()));//-- on another thread!

                Dispatcher.BeginInvoke(() => TaskProcessing(results));
            }
            myResponse.Close();
        }

        private void GetIdea()
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://dev.tuzzit.com/exec/idea_controller.php?function=get_ideas_list&format=json&params%5Bhashcode%5D=" + hash);
            request.CookieContainer = new CookieContainer();
            request.CookieContainer.Add(new Uri("http://dev.tuzzit.com"), (Application.Current as App).Cookies);
            request.BeginGetResponse(new AsyncCallback(ReadWebRequestCallbackIdea), request);
        }

        private void ReadWebRequestCallbackIdea(IAsyncResult callbackResult)
        {
            HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
            HttpWebResponse myResponse = (HttpWebResponse)myRequest.EndGetResponse(callbackResult);

            (Application.Current as App).Cookies = myResponse.Cookies;

            using (StreamReader httpwebStreamReader = new StreamReader(myResponse.GetResponseStream()))
            {
                string results = httpwebStreamReader.ReadToEnd();
                // Dispatcher.BeginInvoke(() => MessageBox.Show(results.ToString()));//-- on another thread!

                Dispatcher.BeginInvoke(() => IdeaProcessing(results));
            }
            myResponse.Close();
        }

        private void GetDoc()
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://dev.tuzzit.com/exec/doc_controller.php?function=get_docs_list&format=json&params%5Bhashcode%5D=" + hash);
            request.CookieContainer = new CookieContainer();
            request.CookieContainer.Add(new Uri("http://dev.tuzzit.com"), (Application.Current as App).Cookies);
            request.BeginGetResponse(new AsyncCallback(ReadWebRequestCallbackDoc), request);
        }

        private void ReadWebRequestCallbackDoc(IAsyncResult callbackResult)
        {
            HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
            HttpWebResponse myResponse = (HttpWebResponse)myRequest.EndGetResponse(callbackResult);

            (Application.Current as App).Cookies = myResponse.Cookies;

            using (StreamReader httpwebStreamReader = new StreamReader(myResponse.GetResponseStream()))
            {
                string results = httpwebStreamReader.ReadToEnd();
                // Dispatcher.BeginInvoke(() => MessageBox.Show(results.ToString()));//-- on another thread!

                Dispatcher.BeginInvoke(() => DocProcessing(results));
            }
            myResponse.Close();
        }

        private void GetTeam()
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://dev.tuzzit.com/exec/team_controller.php?function=get_team_list&format=json&params%5Bhashcode%5D=" + hash);
            request.CookieContainer = new CookieContainer();
            request.CookieContainer.Add(new Uri("http://dev.tuzzit.com"), (Application.Current as App).Cookies);
            request.BeginGetResponse(new AsyncCallback(ReadWebRequestCallbackTeam), request);
        }

        private void ReadWebRequestCallbackTeam(IAsyncResult callbackResult)
        {
            HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
            HttpWebResponse myResponse = (HttpWebResponse)myRequest.EndGetResponse(callbackResult);

            (Application.Current as App).Cookies = myResponse.Cookies;



            using (StreamReader httpwebStreamReader = new StreamReader(myResponse.GetResponseStream()))
            {
                string results = httpwebStreamReader.ReadToEnd();
                // Dispatcher.BeginInvoke(() => MessageBox.Show(results.ToString()));//-- on another thread!

                Dispatcher.BeginInvoke(() => TeamProcessing(results));
            }
            myResponse.Close();
        }

        private void IdeaProcessing(string response)
        {
            response = @"{""responseData"": " + response + "}";

            JObject o = JObject.Parse(response);
            List<ModeleIdea> listIdea = new List<ModeleIdea>();

            foreach (JObject tmp in o["responseData"])
            {
                ModeleIdea vartmp = new ModeleIdea(

                        (string)tmp.SelectToken("title"),
                        (string)tmp.SelectToken("description"),
                        (string)tmp.SelectToken("owner_user_id")

                );
                listIdea.Add(vartmp);

            }

            IdeaList.ItemsSource = listIdea;

        }

        private void TaskProcessing(string response)
        {
            response = @"{""responseData"": " + response + "}";

            JObject o = JObject.Parse(response);
            List<ModeleTask> listTask = new List<ModeleTask>();


            foreach (JObject tmp in o["responseData"])
            {
                ModeleTask vartmp = new ModeleTask(

                        (string)tmp.SelectToken("title"),
                        (string)tmp.SelectToken("description"),
                        (string)tmp.SelectToken("owner_user_id")

                );
                listTask.Add(vartmp);

            }

            TaskList.ItemsSource = listTask;

        }

        private void DocProcessing(string response)
        {
            response = @"{""responseData"": " + response + "}";

            JObject o = JObject.Parse(response);
            List<ModeleDoc> listDoc = new List<ModeleDoc>();


            foreach (JObject tmp in o["responseData"])
            {
                ModeleDoc vartmp = new ModeleDoc(

                        (string)tmp.SelectToken("title"),
                        (string)tmp.SelectToken("filepath"),
                        (string)tmp.SelectToken("owner_id")

                );
                listDoc.Add(vartmp);

            }

            DocList.ItemsSource = listDoc;

        }

        private void TeamProcessing(string response)
        {
            response = @"{""responseData"": " + response + "}";

            JObject o = JObject.Parse(response);
            List<ModeleTeam> listTeam = new List<ModeleTeam>();


            foreach (JObject tmp in o["responseData"])
            {
                ModeleTeam vartmp = new ModeleTeam(

                        (string)tmp.SelectToken("title"),
                        (string)tmp.SelectToken("mission"),
                        (string)tmp.SelectToken("manager_id")

                );
                listTeam.Add(vartmp);

            }

            TeamList.ItemsSource = listTeam;

        }


        private void Download(object sender, System.Windows.Input.GestureEventArgs e)
        {
            ModeleDoc item = (ModeleDoc)this.DocList.SelectedItem;         
            WebBrowserTask webBrowserTask = new WebBrowserTask();
            webBrowserTask.Uri = new Uri("http://dev.tuzzit.com/" + item.Path);
            webBrowserTask.Show();

        }


        private void AddItem(object sender, EventArgs e)
        {
            ResourceManager resourceManager = new ResourceManager("Tuzzit.AppResources", GetType().Assembly);
            MessageBox.Show((String)resourceManager.GetObject("ProjetPivotMessageBoxNotImplemented"));
        }
        private void About(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/About.xaml", UriKind.RelativeOrAbsolute));
        }

        private void Refresh(object sender, EventArgs e)
        {
            GetTask();
            GetIdea();
            GetDoc();
            GetTeam();
        }

        private void UserLogout(object sender, EventArgs e)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://dev.tuzzit.com/exec/logout.php?hashcode=55532d2a2d3131352d2a2d");
            request.BeginGetResponse(new AsyncCallback(ReadCallback), request);
        }

        private void ReadCallback(IAsyncResult callbackResult)
        {
            HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
            HttpWebResponse myResponse = (HttpWebResponse)myRequest.EndGetResponse(callbackResult);

            using (StreamReader httpwebStreamReader = new StreamReader(myResponse.GetResponseStream()))
            {
                string results = httpwebStreamReader.ReadToEnd();
                Dispatcher.BeginInvoke(() => logout_success(results.Trim()));
            }
            myResponse.Close();
        }

        private void logout_success(string res)
        {
            //MessageBox.Show("#"+res.ToString()+"#");
            if (res != "")
            {
                MessageBox.Show("An error occured !");
            }
            else
            {
                ResourceManager resourceManager = new ResourceManager("Tuzzit.AppResources", GetType().Assembly);
                MessageBox.Show((String)resourceManager.GetObject("ProjetPivotMessageBoxLoggedOut"));          
                NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.RelativeOrAbsolute));
            }
                                      
        }

        protected override void OnOrientationChanged(OrientationChangedEventArgs e)
        {
            if ((e.Orientation & PageOrientation.Landscape) == PageOrientation.Landscape)
            {
                r_idea.Width = 632;
                r_doc.Width = 632;
                r_task.Width = 632;
                r_team.Width = 632;
                
                
            }
            else
            {
                //faire des choses pour le mode portrait
                r_idea.Width = 456;
                r_doc.Width = 456;
                r_task.Width = 456;
                r_team.Width = 456;
                
            }
            base.OnOrientationChanged(e);
        }

        private void Settings(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/UserSettings.xaml", UriKind.RelativeOrAbsolute));
        }

    }
}